#include "NewtonInterpolation.hpp"
#include <stdexcept>

NewtonInterpolation::NewtonInterpolation(const std::vector<double>& x, const std::vector<double>& y) : x(x), y(y) {
    if (x.size() != y.size()) {
        throw std::invalid_argument("The sizes of x and y must be equal.");
    }
    int n = x.size();
    std::vector<std::vector<double>> divided_diff;
    divided_diff.resize(n);
    for (int i = 0; i < n; i++)
    {
        divided_diff[i].resize(i + 1);
        divided_diff[i][0] = y[i];
    }
    for (int j = 1; j < n; j++)
    {
        for (int i = j; i < n; i++)
        {
            divided_diff[i][j] = (divided_diff[i][j - 1] - divided_diff[i - 1][j - 1]) / (x[i] - x[i - j]);
        }
    }
    for (int i = 0; i < n; i++)
    {
        z.push_back(divided_diff[i][i]);
    }
}

NewtonInterpolation::NewtonInterpolation(const std::vector<double>& x, std::function<double(double)> f) : x(x) {
    y.resize(x.size());
    for (size_t i = 0; i < x.size(); ++i) {
        y[i] = f(x[i]);
    }
    int n = x.size();
    std::vector<std::vector<double>> divided_diff;
    divided_diff.resize(n);
    for (int i = 0; i < n; i++)
    {
        divided_diff[i].resize(i + 1);
        divided_diff[i][0] = y[i];
    }
    for (int j = 1; j < n; j++)
    {
        for (int i = j; i < n; i++)
        {
            divided_diff[i][j] = (divided_diff[i][j - 1] - divided_diff[i - 1][j - 1]) / (x[i] - x[i - j]);
        }
    }
    for (int i = 0; i < n; i++)
    {
        z.push_back(divided_diff[i][i]);
    }
}

double NewtonInterpolation::operator()(double eval_x) const {
    int n = x.size();
    double result = 0;

    for (int i = n-1; i >=0; --i) {
        result = result*(eval_x-x[i]) + z[i];
        
    }
    return result;
}

int NewtonInterpolation::getDegree() const {
    return static_cast<int>(x.size()) - 1;
}

// 由于声明为纯虚函数，这里不需要实现
double NewtonInterpolation::derivative(double x) const {
    throw std::runtime_error("Derivative is not implemented in NewtonInterpolation.");
    return 0; // 这一行永远不会被执行，但需要存在以避免编译错误
}